<template>
  <!-- 门诊医生-处方 -->
  <div class="w-full h-full relative">
    <a-spin :spinning="thisStore.loading">
      <template v-for="(tableItem, index) in thisStore.tableList" :key="tableItem.tableKey">
        <div class="flex justify-between items-center p-2 mt-2 table-header">
          <div class="flex items-center">
            <div class="font-bold w-10 mr-2">处方{{ index + 1 }}</div>
            <a-select
              v-model:value="tableItem.medicineType"
              class="w-[72px]"
              :options="[
                { label: '普', value: '0' },
                { label: '精一', value: '1' },
                { label: '精二', value: '2' },
                { label: '麻醉', value: '3' }
              ]"
            />
            <!-- 药房 -->
            <SelectDrugRoom
              :value="tableItem.drugStoreName"
              :params="{ storetype: 1, isLocalStore: 0 }"
              select-first
              class="w-52 ml-2"
              :disabled="!!tableItem.dataSource[0]?.cfbh"
              @select="onChangeDrugRoom($event, tableItem)"
            />
            <span class="flex-center ml-2">
              显示已作废医嘱
              <a-switch v-model:checked="thisStore.switchList[tableItem.cfbh]" class="mx-2" @click="thisStore.getData(cfbh, $event)" />
            </span>
          </div>

          <a-space>
            <a-button ghost type="primary" @click="onOpenTemplate(tableItem.tableKey)">处方套餐</a-button>
            <a-button>注射输液单</a-button>
            <a-button @click="onPrint(tableItem)">打印处方</a-button>
            <BaseButton :confirm-text="`确认删除处方${index + 1}？`" :icon="h(DeleteOutlined)" danger size="small" @click="thisStore.deleteTable(tableItem)" />
          </a-space>
        </div>
        <!-- 处方表格 -->
        <TableItem :ref="(e) => getRef(e, tableItem.tableKey)" :table-key="tableItem.tableKey" />
      </template>
      <!-- 处方模板 -->
    </a-spin>
    <TemplateModal v-model:open="templateModalOpen" @success="onAddTemplate" />
    <a-card class="sticky bottom-0 z-30">
      <a-space class="flex justify-end">
        <a-button @click="thisStore.addTable()">新增处方</a-button>
        <a-button type="primary" class="mr-3" :disabled="thisStore.isHaveNewRow" @click="saveSign()">签署 </a-button>
      </a-space>
    </a-card>
  </div>
</template>
<script setup>
import { ref, h, onMounted } from 'vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import userInfo from '../../store'
import useStore from './store'
import TemplateModal from './TemplateModal'
import TableItem from './TableItem'

const thisStore = useStore()
const thisUserStore = userInfo()
const templateModalOpen = ref(false)
const tableItemRef = ref({})
const currentTableKey = ref()
const tableListId = ref([])
const onOpenTemplate = (tableKey) => {
  thisStore.tableKey = tableKey
  currentTableKey.value = tableKey
  templateModalOpen.value = true
}
const getRef = (e, tableKey) => {
  tableItemRef.value[tableKey] = e
}
const onAddTemplate = async (list) => {
  const isAddSucceed = await thisStore.addTemplate(currentTableKey.value, list)
  isAddSucceed && (templateModalOpen.value = false)
  tableItemRef.value[currentTableKey.value].onCalcTotal()
}

const onPrint = async (current) => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicinePrescriptionPrint', { cfbh: current.cfbh, jzbh: thisUserStore.currentPatient.jzbh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onChangeDrugRoom = async (select, table) => {
  table.drugStoreId = select.id
  table.drugStoreName = select.storeName
}

// 签署
const saveSign = async () => {
  tableListId.value = thisStore.tableList.map((i) => getListId(i.dataSource)).flat()
  if (tableListId.value[0] === '') {
    return message.error('不能为空')
  }
  const { code, msg } = await post('/outp/mzys/signedDoctor', {
    yzid: tableListId.value,
    yzzt: 1
  })
  if (code !== 0) return message.error(msg || '签署失败')
  message.success(msg)
  await thisStore.getData()
}

// 获取所有医嘱id
const getListId = (children) => {
  return children.reduce((ids, child) => {
    ids.push(child.id)
    if (child.children) {
      ids = ids.concat(getListId(child.children))
    }
    return ids
  }, [])
}

onMounted(() => {
  thisStore.tableList = []
  thisStore.getData()
})
</script>
<style lang="less" scoped>
.table-header {
  background-color: var(--thin-color);
  border-radius: 2px;
  &:first-child {
    margin-top: 0;
    border: none;
  }
}
</style>
